using System;
using System.Collections.Generic;
using System.Text;
using Autorun;
using System.Diagnostics;
using System.IO;
using System.Security;

namespace Samples
{
    class ShellExecute : TaskBase
    {
        #region "Parameter names"
        private const string PARM_FILENAME = "FileName";
        private const string PARM_ARGUMENTS = "Arguments";
        private const string PARM_USERNAME = "UserName";
        private const string PARM_PASSWORD = "Password";
        private const string PARM_DOMAIN = "Domain";
        #endregion

        #region "Overriden methods"
        protected override void InitializeParameterList()
        {
            Parameters.Add(PARM_FILENAME, null);
            Parameters.Add(PARM_ARGUMENTS, null);
            Parameters.Add(PARM_USERNAME, null);
            Parameters.Add(PARM_PASSWORD, null);
            Parameters.Add(PARM_DOMAIN, null);
        }

        protected override void PreProcess()
        {
            // === Verify the parameters =====================================
            if (File.Exists(Parameters[PARM_FILENAME]) == false)
                throw new ArgumentException(string.Format("Application '{0}' has not been found", Parameters[PARM_FILENAME]));

            if (Parameters[PARM_PASSWORD] == null)
                Parameters[PARM_PASSWORD] = "";
        }

        protected override void Process()
        {
            ProcessStartInfo psi;
            SecureString ss;
            System.Diagnostics.Process p;

            // === Encrypt the password ======================================
            ss = new System.Security.SecureString();
            foreach (char letter in Parameters[PARM_PASSWORD])
                ss.AppendChar(letter);
            ss.MakeReadOnly();

            // === Prepare the process start information bloc ================
            psi = new ProcessStartInfo(Parameters[PARM_FILENAME]);
            psi.Arguments = Parameters[PARM_ARGUMENTS];
            psi.UserName = Parameters[PARM_USERNAME];
            psi.Password = ss;
            psi.Domain = Parameters[PARM_DOMAIN];
            psi.UseShellExecute = false;

            p = System.Diagnostics.Process.Start(psi);
            p.WaitForExit();
        }

        protected override void PostProcess()
        {
            // === No cleanup tasks required ==================================
        }
        #endregion
    }
}